from controllers.Base import *
from settings import g_settings,g_logger
from utils.Utils import xc_base64_decode_result, xc_get_timestamp, xc_gen_random_code
from tornado.websocket import WebSocketHandler


class WsController(WebSocketHandler):
    # 成员属性
    start_timestamp = 0
    start_date_str = None
    start_xcms_name = None
    def get_request_ip(self):
        request_ip = self.request.headers.get("X-Real-IP") or self.request.headers.get("X-Forwarded-For") or \
                    self.request.remote_ip
        return request_ip

    def open(self):
        g_logger.info("open() ip=%s,uri=%s" % (self.get_request_ip(),self.request.uri))
        try:
            self.start_timestamp = xc_get_timestamp()
            self.start_date_str = datetime.now().strftime("%Y/%m/%d %H:%M:%S")

            param_str = self.request.uri[len(self.request.path)+1:]
            __ret,__msg,strs = xc_base64_decode_result(key=g_settings.appKey,secret=g_settings.appSecret,result_base64_safe=param_str)
            if __ret:
                if len(strs) >= 7:
                    # xcms注册成功
                    xcms_name = strs[0]
                    xcms_describe = strs[1]
                    xcms_version = strs[2]
                    xcms_flag = strs[3]
                    xcms_systemName = strs[4] # xcms部署的操作系统
                    xcms_machineNode = strs[5] # xcms部署的机器名称
                    xcms_host = strs[6] # xcms的config.json配置的host参数

                    self.start_xcms_name = xcms_name
                    if g_xcmsDict.get(xcms_name):
                        del g_xcmsDict[xcms_name]

                    val = {
                        "ws": self,
                        "timestamp": self.start_timestamp,
                        "date": self.start_date_str,
                        "xcms_name": xcms_name,
                        "xcms_describe": xcms_describe,
                        "xcms_version": xcms_version,
                        "xcms_flag": xcms_flag,
                        "xcms_systemName": xcms_systemName,
                        "xcms_machineNode": xcms_machineNode,
                        "xcms_host": xcms_host
                    }
                    g_xcmsDict[xcms_name] = val

                    #TODO添加测试数据
                    """
        
                    for j in range(1,31):
                        xcms_name_j =  "test_%d" % j
                        val_j = {
                            "ws": self,
                            "timestamp": self.start_timestamp,
                            "date": self.start_date_str,
                            "xcms_name": xcms_name_j,
                            "xcms_describe": "test_%d" % j,
                            "xcms_version": "test_%d" % j,
                            "xcms_flag": "test_%d" % j,
                            "xcms_systemName": "test_%d" % j,
                        }
                        g_xcmsDict[xcms_name_j] = val_j
                    """

                    g_logger.info("open() open success, strs=%s"%str(strs))
                else:
                    raise Exception("open() strs error,strs=%s" % str(strs))
            else:
                # xcms注册失败
                raise Exception("open() verify error, param_str=%s"%str(param_str))
        except Exception as e:
            g_logger.error(str(e))
            self.close()

    def on_message(self, message):
        try:
            message = json.loads(message)  # data转换为json格式的message
            message_type = message.get("message_type","message_type")
            message_uuid = message.get("message_uuid","message_uuid")
            if message_type == "CmdXcmsStreamList":
                g_logger.info("on_message() message=%s" % str(message))
                g_messageCmdXcmsStreamList.setdefault(message_uuid,{
                    "message":message,
                    "message_timestamp":xc_get_timestamp(),
                    "xcms_start_timestamp":self.start_timestamp,
                    "xcms_start_date": self.start_date_str,
                    "xcms_name": self.start_xcms_name
                })
            elif message_type == "CmdXcmsLiveStart":
                g_logger.info("on_message() message=%s" % str(message))
                g_messageCmdXcmsLiveStart.setdefault(message_uuid,{
                    "message":message,
                    "message_timestamp":xc_get_timestamp(),
                    "xcms_start_timestamp":self.start_timestamp,
                    "xcms_start_date": self.start_date_str,
                    "xcms_name": self.start_xcms_name
                })
            elif message_type == "CmdXcmsLiveStop":
                g_logger.info("on_message() message=%s" % str(message))
                g_messageCmdXcmsLiveStop.setdefault(message_uuid,{
                    "message":message,
                    "message_timestamp":xc_get_timestamp(),
                    "xcms_start_timestamp":self.start_timestamp,
                    "xcms_start_date": self.start_date_str,
                    "xcms_name": self.start_xcms_name
                })
            elif message_type == "CmdXcmsRecordTimeline":
                g_logger.info("on_message() message=%s" % str(message))
                g_messageCmdXcmsRecordTimeline.setdefault(message_uuid,{
                    "message":message,
                    "message_timestamp":xc_get_timestamp(),
                    "xcms_start_timestamp":self.start_timestamp,
                    "xcms_start_date": self.start_date_str,
                    "xcms_name": self.start_xcms_name
                })
            elif message_type == "CmdXcmsRecordFilename":
                g_logger.info("on_message() message=%s" % str(message))
                g_messageCmdXcmsRecordFilename.setdefault(message_uuid, {
                    "message": message,
                    "message_timestamp": xc_get_timestamp(),
                    "xcms_start_timestamp": self.start_timestamp,
                    "xcms_start_date": self.start_date_str,
                    "xcms_name": self.start_xcms_name
                })
            elif message_type == "CmdXcmsStreamAddProxy":
                g_logger.info("on_message() message=%s" % str(message))
                g_messageCmdXcmsStreamAddProxy.setdefault(message_uuid, {
                    "message": message,
                    "message_timestamp": xc_get_timestamp(),
                    "xcms_start_timestamp": self.start_timestamp,
                    "xcms_start_date": self.start_date_str,
                    "xcms_name": self.start_xcms_name
                })
            elif message_type == "CmdXcmsStreamDelProxy":
                g_logger.info("on_message() message=%s" % str(message))
                g_messageCmdXcmsStreamDelProxy.setdefault(message_uuid, {
                    "message": message,
                    "message_timestamp": xc_get_timestamp(),
                    "xcms_start_timestamp": self.start_timestamp,
                    "xcms_start_date": self.start_date_str,
                    "xcms_name": self.start_xcms_name
                })
            elif message_type == "CmdXcmsStreamPtz":
                g_logger.info("on_message() message=%s" % str(message))
                g_messageCmdXcmsStreamPtz.setdefault(message_uuid, {
                    "message": message,
                    "message_timestamp": xc_get_timestamp(),
                    "xcms_start_timestamp": self.start_timestamp,
                    "xcms_start_date": self.start_date_str,
                    "xcms_name": self.start_xcms_name
                })
            elif message_type == "heart":
                forward_stream = message.get("forward_stream")
                for app_name ,fws in forward_stream.items():
                    dst_live_app = fws.get("dst_live_app")
                    dst_live_name = fws.get("dst_live_name")
                    __info = g_xcnvsMediaApi.getMediaInfo(app=dst_live_app,name=dst_live_name)
                    if __info.get("ret"):
                        forward_stream[app_name]["online"] = 1
                        forward_stream[app_name]["totalReaderCount"] = __info.get("totalReaderCount")
                    else:
                        forward_stream[app_name]["online"] = 0
                        forward_stream[app_name]["totalReaderCount"] = 0

                ack_data = {
                    "message_type": message_type,
                    "message_uuid": message_uuid,
                    "code": 1000,
                    "msg": "ack success",
                    "forward_stream": forward_stream
                }
                ack_data_message = json.dumps(ack_data)
                self.write_message(ack_data_message)
            else:
                g_logger.error("not supported message_type:%s"%message_type)

        except Exception as e:
            g_logger.error("on_message() error=%s, message=%s" % (str(e),str(message)))

    def on_close(self):
        g_logger.info("on_close()")

        if self.start_xcms_name:
            if g_xcmsDict.get(self.start_xcms_name):
                del g_xcmsDict[self.start_xcms_name]

    def check_origin(self, origin):
        g_logger.info("check_origin() origin=%s"%(str(origin)))
        return True  # 允许WebSocket的跨域请求

    def send_cmd(self,cmd_data):
        __cmd_data_message = json.dumps(cmd_data)
        self.write_message(__cmd_data_message)